package com.yingxue.demo.shiro;

import com.yingxue.demo.constant.Constant;
import com.yingxue.demo.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Value;
import java.util.Collection;

/**
 * @Package: com.company.demo.shiro.realm
 * @Author: Mr.Waves
 * @Date: 2020-02-28 10:18
 * @Description: 自定义realm
 **/

public class CustomRealm extends AuthorizingRealm {

    @Value("${shiro.realmName}")
    private String realmName;


    public CustomRealm() {
        super.setName(realmName);
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof CustomUsernamePasswordToken;
    }

    /*
     * 执行授权逻辑
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 将JWT中的角色信息和权限信息传递给授权器
        String accessToken = (String) principalCollection.getPrimaryPrincipal();
        Claims claims = JWTUtil.getClaimsFromToken(accessToken);
        if (claims.get(Constant.JWT_ROLES_KEY) != null) {
            authorizationInfo.addRoles((Collection<String>) claims.get(Constant.JWT_ROLES_KEY));
        }
        if (claims.get(Constant.JWT_PERMISSIONS_KEY) != null) {
            authorizationInfo.addStringPermissions((Collection<String>) claims.get(Constant.JWT_PERMISSIONS_KEY));
        }

        return authorizationInfo;
    }

    /*
     * 执行认证逻辑
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        CustomUsernamePasswordToken token = (CustomUsernamePasswordToken) authenticationToken;
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), realmName);
        return authenticationInfo;
    }
}
